import React, { Component } from "react";
import { Table, Select, Row, Col, Form, DatePicker, Tooltip } from "antd";
import { connect } from "dva";
import moment from "moment";
import InputOnBlur from "./components/InputOnBlur";
import styles from "./PushDetail.less";

const FormItem = Form.Item;
const { RangePicker } = DatePicker;
const dateFormat = "YYYY/MM/DD";
const { Option } = Select;

const formItemLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 16 }
};

const columns = [
  {
    title: "推送应用",
    dataIndex: "appName"
  },
  {
    title: "推送场景",
    dataIndex: "sceneName",
    width: "16.5%"
  },
  {
    title: "推送民警",
    dataIndex: "objectAppUserName",
    width: "9.5%"
  },
  {
    title: "推送时间",
    dataIndex: "pushTime",
    width: "9.5%"
  },
  {
    title: "是否有帮助",
    dataIndex: "isHelp",
    width: "9.5%",
    render: text => (text ? "有帮助" : "无帮助")
  },
  {
    title: "消息内容",
    dataIndex: "content",
    width: "19%",
    render: text =>
      text && text.length > 15 ? (
        <Tooltip placement="top" title={text} arrowPointAtCenter>
          <span>{`${text.substring(0, 15)}……`}</span>
        </Tooltip>
      ) : (
        text
      )
  },
  {
    title: "反馈内容",
    dataIndex: "evaluation",
    width: "19%",
    render: text =>
      text && text.length > 15 ? (
        <Tooltip placement="top" title={text} arrowPointAtCenter>
          <span>{`${text.substring(0, 15)}……`}</span>
        </Tooltip>
      ) : (
        text
      )
  }
];

// 查询数据
const handleSearch = (dispatch, values) => {
  let startTime;
  let endTime;
  const {
    time = [],
    appId,
    orgCode,
    objectAppUserId,
    isRead,
    content
  } = values;
  if (time.length > 0) {
    startTime = time[0].format(dateFormat);
    endTime = time[1].add(1, "days").format(dateFormat);
  }
  const payload = {
    appId,
    orgCode,
    startTime,
    endTime,
    objectAppUserId,
    isRead,
    content
  };
  dispatch({ type: "pushDetail/getDataList", payload });
};

@connect(stores => ({
  pushDetailData: stores.pushDetail
}))
@Form.create({
  // 在表单值发生改变时自动发送查询请求
  onValuesChange: (props, changedValues, allValues) => {
    handleSearch(props.dispatch, allValues);
  }
})
class pushDetail extends Component {
  componentDidMount() {
    const {
      dispatch,
      form: { setFieldsValue }
    } = this.props;
    dispatch({
      type: "pushDetail/getDataList",
      payload: {
        startTime: moment().format(dateFormat),
        endTime: moment()
          .add(1, "days")
          .format(dateFormat)
      }
    });
    dispatch({ type: "pushDetail/getAppList" });
    dispatch({ type: "pushDetail/getOrgList" }).then(({ orgCode } = {}) => {
      setFieldsValue({
        orgCode
      });
    });
  }

  // 列表分页发生改变时
  handleTableChange = (pagination = {}) => {
    const { current: pageIndex, pageSize } = pagination;
    this.props.dispatch({
      type: "pushDetail/set/filter",
      payload: { pageIndex, pageSize }
    });
    const values = this.props.form.getFieldsValue();
    handleSearch(this.props.dispatch, values);
  };

  render() {
    const { pushDetailData } = this.props;
    const {
      appList = [],
      orgList = [],
      dataList = [],
      filter,
      totalCount,
      totalPage
    } = pushDetailData;
    // 获取应用列表并转化为选择项
    const appListOption = appList.map(item => (
      <Option key={item.appId}>{item.appName}</Option>
    ));
    // 获取规则列表并转化为选择项
    const orgListOption = orgList.map(item => (
      <Option key={item.orgCode} value={item.orgCode}>
        {item.orgName}
      </Option>
    ));
    const { getFieldDecorator } = this.props.form;
    return (
      <div className={styles.root}>
        <div className={styles.setDiv}>
          <span className={styles.title}>推送明细</span>
        </div>
        <Row>
          <Col span={8}>
            <FormItem {...formItemLayout} label="推送应用">
              {getFieldDecorator("appId", {
                rules: []
              })(
                <Select
                  placeholder="请选择推送应用"
                  style={{ width: "100%" }}
                  showSearch
                  allowClear
                  optionFilterProp="children"
                >
                  {appListOption}
                </Select>
              )}
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem {...formItemLayout} label="推送机构">
              {getFieldDecorator("orgCode")(
                <Select
                  placeholder="请选择推送机构"
                  style={{ width: "100%" }}
                  showSearch
                  optionFilterProp="children"
                >
                  {orgListOption}
                </Select>
              )}
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem {...formItemLayout} label="时间范围">
              {getFieldDecorator("time", {
                initialValue: [moment(), moment()],
                rules: []
              })(<RangePicker format={dateFormat} onChange={this.onSearch} />)}
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span={8}>
            <FormItem {...formItemLayout} label="推送民警">
              {getFieldDecorator("objectAppUserId", {
                rules: []
              })(<InputOnBlur placeholder="请输入推送民警身份证号" />)}
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem {...formItemLayout} label="是否已读">
              {getFieldDecorator("isRead", {
                rules: []
              })(
                <Select
                  placeholder="请选择"
                  style={{ width: "100%" }}
                  allowClear
                >
                  <Option key="1">已读</Option>
                  <Option key="0">未读</Option>
                </Select>
              )}
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem {...formItemLayout} label="消息内容">
              {getFieldDecorator("content", {
                rules: []
              })(<InputOnBlur placeholder="请输入消息内容" />)}
            </FormItem>
          </Col>
        </Row>
        <Table
          columns={columns}
          dataSource={dataList}
          rowKey="id"
          size="middle"
          onChange={this.handleTableChange}
          pagination={{
            total: totalCount,
            pageSize: filter.pageSize,
            current: filter.pageIndex,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: total =>
              `共 ${total} 条记录 第 ${filter.pageIndex}/ ${totalPage}页`
          }}
        />
      </div>
    );
  }
}

export default pushDetail;
